package com.func.boom.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.func.boom.dao.dto.RegisterDto;
import com.func.boom.entity.TResourceModule;
import com.func.boom.entity.TResourceRole;
import com.func.boom.service.ModuleService;
import com.func.boom.service.RoleService;
import com.func.boom.service.UserService;
import com.func.boom.utils.ResultEntity;
import com.func.boom.utils.jwt.Authentication;
import com.func.boom.utils.jwt.JwtHelper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Yulei
 * @date 2020-08-13 16:34:02
 * @Description
 */
@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {

    @Resource
    private UserService userService;
    @Resource
    private ModuleService moduleService;
    @Resource
    private RoleService roleService;

    /**
     * 登录
     * @param authentication
     * @return
     */
    @RequestMapping("/getToken")
    public ResultEntity<?> login(@RequestBody Authentication authentication){
        return userService.login(authentication);
    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    @RequestMapping("/info")
    public ResultEntity<?> info(@RequestParam("token") String token){
        Claims claims = JwtHelper.parseJWT(token);
        List<TResourceModule> moduleList = moduleService.selectModule();
        //获取用户权限
        QueryWrapper<TResourceRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", claims.get("userId"));
        TResourceRole tResourceRole = roleService.getOne(queryWrapper);
        Map map = new HashMap<>();
        map.put("phone", claims.get("userName"));
        map.put("module", moduleList);
        map.put("role", tResourceRole.getModules());
        return ResultEntity.success(map);
    }

    /**
     * 注册账号
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public ResultEntity<?> register(@RequestBody RegisterDto user){
        return userService.register(user);
    }

    /**
     * 获取验证码
     * @param response
     * @param type 获取验证码的不同redis key的接口
     */
    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, @RequestParam("phone") String phone, @RequestParam("type") Integer type){
        userService.getCaptcha(response, phone, type);
    }

}
